const winston = require('winston');
const { createLogger, format, transports } = winston;
const DailyRotateFile = require('winston-daily-rotate-file');
const fs = require('fs');
const path = require('path');

// 确保日志目录存在
const logDir = path.join(__dirname, 'log');
if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir, { recursive: true });
}

// 定义日志格式
const logFormat = format.combine(
    format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss' }),
    format.printf(info => `${info.timestamp} [${info.level}]: ${info.message}`)
);

// 创建按日期滚动的文件传输器
const fileRotateTransport = new DailyRotateFile({
    filename: path.join(logDir, '%DATE%.log'),
    datePattern: 'YYYY-MM-DD',
    maxSize: '20m',
    maxFiles: '14d',
    format: logFormat
});

// 创建logger实例
const logger = createLogger({
    level: 'info',
    format: logFormat,
    transports: [
        // 控制台日志
        new transports.Console({
            format: format.combine(
                format.colorize(),
                logFormat
            )
        }),
        // 文件日志
        fileRotateTransport
    ]
});

// 记录未捕获的异常
process.on('uncaughtException', (error) => {
    logger.error(`未捕获的异常: ${error.message}`);
    logger.error(error.stack);
    process.exit(1);
});

// 记录未处理的Promise拒绝
process.on('unhandledRejection', (reason, promise) => {
    logger.error(`未处理的Promise拒绝: ${reason}`);
});

module.exports = logger; 